package cn.itsource.service.impl;

import cn.itsource.domain.Goods;
import cn.itsource.lock.ItsourceLock;
import cn.itsource.lock.ZookeeperDistributedLock;
import cn.itsource.mapper.GoodsMapper;
import cn.itsource.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;

@Service
public class GoodsServiceImpl_zookeeper implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public void updateNum(Map<String,Object> params) {
        Long goodsId = (Long) params.get("id");
        Integer num = (Integer) params.get("num");

        String resourceName = "goods_"+goodsId;
        ItsourceLock lock = new ZookeeperDistributedLock();
        try{
            lock.lock(resourceName);
            System.out.println(Thread.currentThread().getName()+" get lock！");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(System.currentTimeMillis());
            //通过商品id获取商品  3
            Goods goods = goodsMapper.laodById(goodsId);
            System.out.println(goods);
            System.out.println(goods.getCount()+":"+num);
            if (goods.getCount()>=num){
                goodsMapper.updateNum(params);
                System.out.println(Thread.currentThread().getName()+"buy "+num+"！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            if (lock != null) {
                lock.unlock(resourceName);
            }
        }
    }

    @Override
    public Goods getById(Long id) {
        return goodsMapper.laodById(1L);
    }
}
